package com.wl.controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/websocket")
public class WebSocket {
    //    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<WebSocket, String> webSocketMap = new ConcurrentHashMap<>();

    private javax.websocket.Session session = null;

    @OnOpen
    public void onOpen(Session session) {
//        InetSocketAddress remoteAddress = WebsocketUtil.getRemoteAddress(session);
        this.session = session;
//        webSocketSet.add(this);     //加入set中
        //session.getBasicRemote().sendText("Connection Established");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        webSocketMap.put(this, message);
    }

    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(this);
    }


//    @OnError
//    public void onError(Session session, Throwable t) {
//        t.printStackTrace();
//    }


    public static void sendMessage(String articleId, String userId) {
//        System.out.println(userId + "审核了");
        //群发消息
        webSocketMap.forEach((k, v) -> {
            if (!v.equals(userId)) {
                k.session.getAsyncRemote().sendText(articleId);
            }
        });
    }
}
